package edu.sias.question.service.impl;


import edu.sias.question.domain.pojo.CourseAndCatalogId;
import edu.sias.question.domain.pojo.Question;
import edu.sias.question.domain.pojo.UserTopic;
import edu.sias.question.domain.vo.TopicVo;
import edu.sias.question.mapper.QuestionMapper;
import edu.sias.question.service.QuestionService;
import edu.sias.question.utils.EsCopy;
import edu.sias.question.utils.Esutils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 题库业务实现类
 */
@Service
public class QuestionServiceImpl implements QuestionService {
    @Autowired
    private EsCopy esCopy;
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private Esutils esutils;
    /**
     * 分页查询题库列表
     */
    @Override
    public List<Question> findList(String  courseName, String QuestionCode) {

        return questionMapper.selectQuestionList(courseName , QuestionCode);
    }

    /**
     * 新增或更新题目
     */
    @Override
    @Transactional
    public void addOrUpdate(Question question)  {
        try {
        if (question.getId() == null) {
            // 新增
            questionMapper.insertQuestion(question);
            QuestionDTO questionDTO = new QuestionDTO();
            esCopy.copy(questionDTO, question);
            esutils.add(questionDTO);
        } else {
            // 更新
            QuestionDTO questionDTO = new QuestionDTO();
            esCopy.copy(questionDTO, question);
            questionMapper.updateQuestion(question);
            esutils.deleteById(String.valueOf(question.getId()));
            esutils.add(questionDTO);
        }
        } catch (IOException e) {
            throw new RuntimeException("Elasticsearch operation failed", e); // 转换为 RuntimeException
        }

    }



    /**
     * 分页查询精选题库列表
     */
    @Override
    public List<Question> findClassicList() {
        return questionMapper.selectClassicQuestionList( );
    }
    /**
     * 将题目加入精选 就是收藏
     */
    @Override
    public void updateClassic(int id) {
        //  'classicStatus' not found. Available parameters are [arg1, arg0, param1, param2]",
        questionMapper.updateQuestionClassicStatus(id); // 假设 1 表示精选状态
    }

    /**
     * 根据 ID 查询题目详情
     */
    @Override
    @Transactional
    public QuestionDTO getById(Long id) throws IOException {
        QuestionDTO byId = esutils.getById(String.valueOf(id));

        return byId;
    }

    @Override
    @Transactional
    public void deleteById(Long id) throws IOException {
       esutils.deleteById(String.valueOf(id));
        questionMapper.deleteById(id);
    }
}
